package com.shu.config;

import javax.annotation.Resource;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.shu.security.MyFilterSecurityInterceptor;
import com.shu.security.MyUserDetailService;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	@Resource
	private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
	@Resource
	private MyUserDetailService myUserDetailService;

	
	@Override
	public void configure(WebSecurity web) throws Exception {
		 // 设置不拦截规则
		web.ignoring().antMatchers("/statics/**");
		
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//在正确的位置添加我们自定义的过滤器  
		http
			//.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint()).and()
			.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
			.authorizeRequests()
			.anyRequest().authenticated()
			.antMatchers("/admin/**").hasRole("ADMIN").and()
			.formLogin().and()
			.httpBasic()
		//自定义登录页面
			.and()
			.formLogin().loginPage("/loginPage")
			.loginProcessingUrl("/login")
			.failureUrl("/loginPage?error=1")
			.usernameParameter("username")
			.passwordParameter("password")
			//.successHandler(new AjaxAuthSuccessHandler())
			//.failureHandler(new AjaxAuthFailHandler())
			.permitAll().defaultSuccessUrl("/login");
		
        //如果开启了CSRF 退出则需要使用POST访问，可以使用以下方式解决，但并不推荐
		http.logout()
		.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
		//退出之后跳转的位置,以及删除cookies的名称
		.logoutSuccessUrl("/loginPage")
		.invalidateHttpSession(true);
		
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		 //启用内存用户存储
        /*auth.inMemoryAuthentication()
        .withUser("user1").password("123456").roles("USER").and()
        .withUser("admin").password("admin").roles("USER","ADMIN");*/
		//
        //给予数据库表认证
        /*auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery("select username,password,enable from t_user where username=?")
        .authoritiesByUsernameQuery("select username,rolename from t_role where username=?");
        */
		//配置自定义的用户服务
		
		auth.userDetailsService(myUserDetailService).passwordEncoder(new Md5PasswordEncoder());
	}
	
	
	
}











